package com.autonavi.yunda.yunji.core.config.dingding;

import com.alibaba.fastjson.JSON;
import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cizhong.wcs
 * @date 2022/12/19 7:38 下午
 */
public class DingTalkRobot {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkRobot.class);

    public static void sendMessage(String url, String title, String markdownContent) {
        AmapPreconditions.checkNotNull(url);
        Map<String, String> map = new HashMap<>();
        map.put("msgtype", "markdown");
        HashMap<String, String> maps = new HashMap<>();
        maps.put("title", title);
        maps.put("text", markdownContent);
        map.put("markdown", JSON.toJSONString(maps));
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json");
            post.setEntity(new StringEntity(JSON.toJSONString(map), StandardCharsets.UTF_8));
            HttpResponse response = client.execute(post);
            String entity = EntityUtils.toString(response.getEntity());
            logger.info("sendAclMessage : {}, response : {}", markdownContent, entity);
        } catch (Exception e) {
            logger.error("send acl message exception! message = {}", markdownContent, e);
        }
    }

}
